package com.bw.live.ui

import android.Manifest
import android.animation.ObjectAnimator
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.SurfaceView
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.baweigame.xmpplibrary.XmppManager
import com.baweigame.xmpplibrary.contract.StateListener
import com.bw.common.utils.UserUtils
import com.bw.live.R
import com.bw.live.adapter.ChatAdapter
import com.bw.live.common.XMPPMsgType
import com.bw.live.databinding.ActivityLiveBinding
import com.bw.live.model.entity.ChatEntity
import com.bw.live.widget.GiftBottomDialog
import com.bw.mvicore.common.ConstantValue
import com.bw.mvicore.ui.BaseActivity
import com.google.gson.Gson
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jivesoftware.smack.MessageListener
import org.jivesoftware.smack.packet.Message
import org.jivesoftware.smackx.muc.MultiUserChat
import org.jxmpp.jid.EntityFullJid

class LiveActivity : BaseActivity() {
    private lateinit var binding: ActivityLiveBinding

    //是否主播 true-主播 false-观众
    private var isBroadcastr: Boolean = false

    private lateinit var multiUserChat: MultiUserChat

    private lateinit var adapter: ChatAdapter

    override fun releaseRes() {
    }

    override fun generateContentView(): View {
        binding = ActivityLiveBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()

        val bundle = intent.getBundleExtra(ConstantValue.PARAMS)
        isBroadcastr = bundle?.getBoolean("isBoradcastr")!!

        binding.rvLiveChat.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        adapter = ChatAdapter()
        binding.rvLiveChat.adapter = adapter
    }

    override fun initData() {
        if (isBroadcastr) {
            //创建聊天室
            createChatRoom()
        }
        //加入聊天室
        multiUserChat =
            XmppManager.getInstance().xmppChatRoomManager.joinMultiUserChat(
                UserUtils.getCurrentUser()?.username,
                com.bw.live.common.ConstantValue.ROOM_ID
            )

        /**
         * 接收消息的监听
         */
        XmppManager.getInstance().xmppChatRoomManager.registerMsgListener(multiUserChat, object : MessageListener {
            override fun processMessage(message: Message?) {
                if (message == null) {
                    return
                }
                message.let {
                    val msg = message?.body
                    if (msg == null) {
                        return
                    }
                    val chatEntity = Gson().fromJson(msg, ChatEntity::class.java)
                    if (chatEntity == null) {
                        return
                    }

                    when (chatEntity.msgtype) {
                        XMPPMsgType.TXT -> {
                            runOnUiThread {
                                adapter.appendItem(chatEntity)
                            }

                        }

                        XMPPMsgType.GIFT -> {
                            runOnUiThread {
                                showGift(chatEntity.content)
                            }
                        }

                        XMPPMsgType.ONLINE -> {

                        }

                        XMPPMsgType.OFFLINE -> {

                        }
                    }

                }
            }
        })

        /**
         * 接收状态的监听 比如：有人加入聊天室 或者 离开聊天室
         */
        XmppManager.getInstance().xmppChatRoomManager.registerStateListener(multiUserChat, object : StateListener() {
            override fun joined(participant: EntityFullJid?) {
                super.joined(participant)
//                showMsg("${participant?.asEntityBareJid()?.domain}")

                runOnUiThread {
                    binding.tvLiveAlter.visibility = View.VISIBLE
                    val objectAnimator: ObjectAnimator = ObjectAnimator.ofFloat(
                        binding.tvLiveAlter,
                        "translationX",
                        0.0F,
                        -window.decorView.width.toFloat()
                    )
                    objectAnimator.duration = 3000
                    objectAnimator.interpolator = AccelerateDecelerateInterpolator()
                    objectAnimator.start()
                }


            }

            override fun left(participant: EntityFullJid?) {
                super.left(participant)
            }
        })

    }


    /*
     * 创建聊天室
     */
    private fun createChatRoom() {
        XmppManager.getInstance().xmppChatRoomManager.createRoom<MultiUserChat>(
            com.bw.live.common.ConstantValue.ROOM_ID,
            ""
        )
    }

    private lateinit var giftName: String
    private lateinit var svgaParser: SVGAParser
    override fun initEvent() {

        //发送聊天内容
        binding.tvLiveSend.setOnClickListener {
            val content = binding.etLiveChatcontent.text.toString().trim()
            generateLifeCycleLaunch {
                val chat = ChatEntity(XMPPMsgType.TXT, UserUtils.getCurrentUser()?.username!!, content, "")
                val chatStr = Gson().toJson(chat)
                XmppManager.getInstance().xmppChatRoomManager.sendMessasge(multiUserChat, chatStr)
                withContext(Dispatchers.Main) {
                    adapter.appendItem(chat)
                    binding.etLiveChatcontent.text?.clear()
                }

            }

        }


        svgaParser = SVGAParser(this)
        /**
         * 发送礼物
         */
        binding.tvLiveGift.setOnClickListener {

            val dialog = GiftBottomDialog(LiveActivity@ this)
            dialog.show()
            dialog.selectedListener = {
                giftName = it.txt
            }

            dialog.sendListener = {
                showGift(giftName)
                val chat = ChatEntity(XMPPMsgType.GIFT, UserUtils.getCurrentUser()?.username!!, giftName, "")
                val chatStr = Gson().toJson(chat)
                //发送礼物消息
                XmppManager.getInstance().xmppChatRoomManager.sendMessasge(multiUserChat,chatStr)
            }


        }
    }

    /**
     * 显示礼物
     */
    private fun showGift(svgaRes: String) {
//        val svgaArray = resources.getStringArray(R.array.normal_giftarray)
//            val svgaRes = svgaArray[6]
        svgaParser.decodeFromAssets(svgaRes, object : SVGAParser.ParseCompletion {
            override fun onComplete(videoItem: SVGAVideoEntity) {
                val svgaDrawable = SVGADrawable(videoItem)
                binding.svgaivLiveSvga.loops = 1
                binding.svgaivLiveSvga.setImageDrawable(svgaDrawable)
                binding.svgaivLiveSvga.startAnimation()
                binding.svgaivLiveSvga.callback = object : SVGACallback {
                    override fun onFinished() {
                        binding.svgaivLiveSvga.stopAnimation(true)
                    }

                    override fun onPause() {
                    }

                    override fun onRepeat() {
                    }

                    override fun onStep(frame: Int, percentage: Double) {
                    }

                }

            }

            override fun onError() {
                showMsg("SVGA资源解析失败")
            }

        })
    }

    // 填写声网控制台中获取的 App ID
    private val appId = "d4a845ef1f164465871056da6e4b8ad9"

    // 填写频道名
    private val channelName = "testchannel01"

    // 填写声网控制台中生成的临时 Token
    private val token =
        "007eJxTYGh/8azu/cX/Sy+97aip+f1zkUWX2M9Pd19nXpvDv/pTQtIPBYYUk0QLE9PUNMM0QzMTEzNTC3NDA1OzlESzVJMki8QUy2VC9mkNgYwM25rLWBkZIBDE52UoSS0uSc5IzMtLzTEwZGAAALB/KHY="

    private lateinit var mRtcEngine: RtcEngine

    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        // 成功加入频道回调
        override fun onJoinChannelSuccess(channel: String, uid: Int, elapsed: Int) {
            super.onJoinChannelSuccess(channel, uid, elapsed)
            runOnUiThread { Toast.makeText(this@LiveActivity, "Join channel success", Toast.LENGTH_SHORT).show() }
        }

        // 远端用户或主播加入当前频道回调
        override fun onUserJoined(uid: Int, elapsed: Int) {
            runOnUiThread {
                // 当远端用户加入频道后，显示指定 uid 的远端视频流
                setupRemoteVideo(uid)
            }
        }

        // 远端用户或主播离开当前频道回调
        override fun onUserOffline(uid: Int, reason: Int) {
            super.onUserOffline(uid, reason)
            runOnUiThread { Toast.makeText(this@LiveActivity, "User offline: $uid", Toast.LENGTH_SHORT).show() }
        }
    }

    private fun initializeAndJoinChannel() {
        try {
            // 创建 RtcEngineConfig 对象，并进行配置
            val config = RtcEngineConfig()
            config.mContext = getBaseContext()
            config.mAppId = appId
            config.mEventHandler = mRtcEventHandler
            // 创建并初始化 RtcEngine
            mRtcEngine = RtcEngine.create(config)
        } catch (e: Exception) {
            throw RuntimeException("Check the error.")
        }


        if (isBroadcastr) {
            // 启用视频模块
            mRtcEngine.enableVideo()

            // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
            val container: FrameLayout = findViewById(R.id.local_video_view_container)
            val surfaceView = SurfaceView(getBaseContext())
            container.addView(surfaceView)
            // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
            mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))
            // 开启本地预览
            mRtcEngine.startPreview()


        }
        // 创建 ChannelMediaOptions 对象，并进行配置
        val options = ChannelMediaOptions()
        // 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        if (isBroadcastr)
            options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        else
            options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE

        // 设置频道场景为 BROADCASTING (直播场景)
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
        // 发布麦克风采集的音频
        options.publishMicrophoneTrack = true
        // 发布摄像头采集的视频
        options.publishCameraTrack = true
        // 自动订阅所有音频流
        options.autoSubscribeAudio = true
        // 自动订阅所有视频流
        options.autoSubscribeVideo = true
        // 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名
        // 成功后会触发 onJoinChannelSuccess 回调
        mRtcEngine.joinChannel(token, channelName, 0, options)


    }

    private fun setupRemoteVideo(uid: Int) {
        val container: FrameLayout = findViewById(R.id.local_video_view_container)
        val surfaceView = SurfaceView(getBaseContext())
//        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }

    private val PERMISSION_REQ_ID = 22

    // 获取体验实时音视频互动所需的录音、摄像头等权限
    private fun getRequiredPermissions(): Array<String> {
        // 判断 targetSDKVersion 31 及以上时所需的权限
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

    private fun checkPermissions(): Boolean {
        for (permission in getRequiredPermissions()) {
            val permissionCheck = ContextCompat.checkSelfPermission(this, permission)
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    protected override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        } else {
            ActivityCompat.requestPermissions(this, getRequiredPermissions(), PERMISSION_REQ_ID)
        }

    }

    // 系统权限申请回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        }
    }

    protected override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine!!.stopPreview()
            // 离开频道
            mRtcEngine!!.leaveChannel()

            // 销毁引擎
            RtcEngine.destroy()
        }
    }
}